﻿using System;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml.XPath;
using UnityEditor;
using UnityEngine;

internal class PostProcessPS3Player
{
    private static string scePath = Environment.GetEnvironmentVariable("SCE_PS3_ROOT");

    internal static string CalculateSubmissionAssetPath(string sourcePath, string assetName, string defaultName, string title)
    {
        string path = Path.Combine(sourcePath, assetName);
        if ((assetName.Length > 0) && File.Exists(path))
        {
            return path;
        }
        return Path.Combine(BuildPipeline.GetBuildToolsDirectory(BuildTarget.PS3), "PS3 Submission Package/" + defaultName);
    }

    internal static string GetDLCConfigValue(string DLCConfigPath, string key)
    {
        StreamReader reader = new StreamReader(DLCConfigPath);
        while (!reader.EndOfStream)
        {
            Match match = Regex.Match(reader.ReadLine(), key + @"(\s+)=(\s+)(\w+)", RegexOptions.IgnoreCase);
            if (match.Success)
            {
                return match.Groups[3].Value;
            }
        }
        return string.Empty;
    }

    internal static string GetTitleConfigValue(string XmlFileName, string key)
    {
        XPathDocument document = new XPathDocument(XmlFileName);
        XPathNavigator navigator2 = document.CreateNavigator().SelectSingleNode("//param[@key=\"" + key + "\"]");
        if (navigator2 != null)
        {
            return navigator2.InnerXml;
        }
        return "TEST11111";
    }

    public static void PostProcess(BuildTarget target, BuildOptions options, string installPath, string stagingAreaData, string stagingArea, string playerPackage, string stagingAreaDataManaged, RuntimeClassRegistry usedClassRegistry)
    {
        string titleID = "TEST11111";
        string kLicenseeString = "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0";
        bool needsDrm = PS3BuildSubtarget.HddTitle == EditorUserBuildSettings.ps3BuildSubtarget;
        bool flag2 = PS3BuildSubtarget.PCHosted == EditorUserBuildSettings.ps3BuildSubtarget;
        bool installInBuildsFolder = (options & BuildOptions.InstallInBuildFolder) != BuildOptions.None;
        bool flag4 = (options & BuildOptions.Development) != BuildOptions.None;
        string sourcePath = Path.Combine(Application.dataPath, "PS3 Submission Package");
        string xmlFileName = CalculateSubmissionAssetPath(sourcePath, PlayerSettings.ps3TitleConfigPath, "TITLECONFIG.XML", "Title Config");
        string dLCConfigPath = CalculateSubmissionAssetPath(sourcePath, PlayerSettings.ps3DLCConfigPath, "DLCconfig.txt", "DLC Config");
        string path = CalculateSubmissionAssetPath(sourcePath, PlayerSettings.ps3ThumbnailPath, "ICON0.PNG", "Thumbnail");
        string str7 = CalculateSubmissionAssetPath(sourcePath, PlayerSettings.ps3BackgroundPath, "BACKGROUND0.PNG", "Background");
        string str8 = Path.Combine(sourcePath, PlayerSettings.ps3SoundPath);
        string str9 = Path.Combine(sourcePath, PlayerSettings.ps3TrophyPackagePath);
        bool flag5 = (PlayerSettings.ps3TrophyPackagePath.Length > 0) && File.Exists(str9);
        string str10 = FileUtil.UnityGetFileNameWithoutExtension(installPath) + ".elf";
        if (installInBuildsFolder)
        {
            ResetTarget(playerPackage, true);
        }
        else
        {
            ResetTarget(installPath, true);
        }
        if (!installInBuildsFolder)
        {
            if (needsDrm && (GetTitleConfigValue(xmlFileName, "CATEGORY") != "HG"))
            {
                throw new SystemException("The CATEGORY param key in TITLECONFIG.XML has to be HG for PSN builds");
            }
            if (flag5)
            {
                if (PlayerSettings.ps3TrophyCommId.Length == 0)
                {
                    throw new System.Exception("TropyCommId is missing.");
                }
                if (PlayerSettings.ps3TrophyCommSig.Length == 0)
                {
                    throw new System.Exception("TropyCommSig is missing.");
                }
            }
            titleID = GetTitleConfigValue(xmlFileName, "TITLE_ID");
            Match match = Regex.Match(GetDLCConfigValue(dLCConfigPath, "Klicensee"), @"0x(\w{32})", RegexOptions.IgnoreCase);
            if (!match.Success)
            {
                throw new System.Exception("Invalid format for Klicensee in DLCConfig.txt. Has to be of format Klicensee = 0x0102030405060708090a0b0c0d0e0f10 !");
            }
            kLicenseeString = string.Empty;
            string str13 = match.Groups[1].Value;
            for (int i = 0; i < 0x10; i++)
            {
                kLicenseeString = (kLicenseeString + "0x" + str13[2 * i]) + ((string) str13[(2 * i) + 1]) + ", ";
            }
        }
        if (!Directory.Exists(stagingAreaData + "/Resources"))
        {
            Directory.CreateDirectory(stagingAreaData + "/Resources");
        }
        FileUtil.CopyFileOrDirectory(playerPackage + "/Data/Resources/unity default resources", stagingAreaData + "/Resources/unity default resources");
        if (!installInBuildsFolder)
        {
            if (Directory.Exists(installPath))
            {
                foreach (string str14 in Directory.GetFiles(installPath))
                {
                    FileUtil.DeleteFileOrDirectory(str14);
                }
            }
            else
            {
                Directory.CreateDirectory(installPath);
            }
        }
        string str15 = stagingArea + "/Submission";
        string to = stagingAreaData + "/AOTCompileStep";
        FileUtil.CopyFileOrDirectory(stagingAreaDataManaged, to);
        if (Directory.Exists(str15))
        {
            foreach (string str17 in Directory.GetFiles(str15))
            {
                FileUtil.DeleteFileOrDirectory(str17);
            }
        }
        else
        {
            Directory.CreateDirectory(str15);
        }
        AssemblyReferenceChecker checker = new AssemblyReferenceChecker();
        checker.CollectReferences(to, false, 0f, false);
        string str18 = "Assets/Plugins/PS3";
        string str19 = stagingAreaData + "/Plugins";
        if (Directory.Exists(str18))
        {
            EditorUtility.DisplayProgressBar("Processing plug-ins", "Copying...", 0.95f);
            FileUtil.CopyDirectoryRecursiveForPostprocess(str18, str19, true);
            PRXTools.CreateNativePluginsPRX(needsDrm, to, playerPackage, str19);
        }
        CrossCompileOptions dynamic = CrossCompileOptions.Dynamic;
        if ((!needsDrm || flag4) && EditorUserBuildSettings.explicitNullChecks)
        {
            dynamic |= CrossCompileOptions.ExplicitNullChecks;
        }
        MonoCrossCompile.CrossCompileAOTDirectoryParallel(target, dynamic, stagingAreaDataManaged, to, PlayerSettings.aotOptions);
        MonoCrossCompile.LinkMonoAssembliesPS3(stagingAreaDataManaged, to, checker.GetAssemblyFileNames(), playerPackage);
        PRXTools.CreateMainLibrary(EditorUserBuildSettings.ps3BuildSubtarget, installInBuildsFolder, titleID, kLicenseeString, stagingAreaData, playerPackage);
        EditorUtility.DisplayProgressBar("Stripping bytecode from assemblies", "Stripping bytecode from assemblies", 0.95f);
        MonoAssemblyStripping.MonoCilStrip(target, stagingAreaDataManaged, checker.GetAssemblyFileNames());
        foreach (string str20 in checker.GetAssemblyFileNames())
        {
            if (Path.GetExtension(str20) == ".dll")
            {
                string str21 = Path.Combine(stagingAreaDataManaged, str20);
                string outputFile = Path.Combine(stagingAreaDataManaged, str20 + ".sdat");
                string processFileName = Path.Combine(scePath, "host-win32/bin/make_sdata.exe");
                string[] textArray1 = new string[] { "--format3 -z \"", str21, "\" \"", outputFile, "\"" };
                string inputArguments = string.Concat(textArray1);
                ExternalTool.StartProcess(processFileName, inputArguments, outputFile, true, string.Empty);
                FileUtil.DeleteFileOrDirectory(str21);
            }
        }
        if (Directory.Exists("Assets/StreamingAssets"))
        {
            FileUtil.CopyDirectoryRecursiveForPostprocess("Assets/StreamingAssets", stagingAreaData + "/Raw", true);
        }
        DirectoryInfo info = new DirectoryInfo(to);
        foreach (FileInfo info2 in info.GetFiles("*_verlog.txt"))
        {
            File.Move(Path.Combine(to, info2.Name), Path.Combine(str15, info2.Name));
        }
        DirectoryInfo info3 = new DirectoryInfo(stagingAreaDataManaged);
        foreach (FileInfo info4 in info3.GetFiles("*.map"))
        {
            File.Move(Path.Combine(stagingAreaDataManaged, info4.Name), Path.Combine(str15, info4.Name));
        }
        if (installInBuildsFolder)
        {
            EditorUtility.DisplayProgressBar("Building Player", "Installing in builds folder", 0.95f);
            string str25 = Path.Combine(Unsupported.GetBaseUnityDeveloperFolder(), "build/PS3Player");
            string str26 = Path.Combine(str25, "Media");
            FileUtil.DeleteFileOrDirectory(str26);
            FileUtil.DeleteFileOrDirectory(Path.Combine(str25, "MonoAssembliesPS3.a"));
            FileUtil.MoveFileOrDirectory(Path.Combine(stagingAreaData, "MonoAssembliesPS3.a"), Path.Combine(str25, "MonoAssembliesPS3.a"));
            FileUtil.DeleteFileOrDirectory(to);
            FileUtil.MoveFileOrDirectory(stagingAreaData, str26);
            if (flag5)
            {
                string str27 = str25 + "/TROPDIR/" + PlayerSettings.ps3TrophyCommId;
                FileUtil.DeleteFileOrDirectory(str27);
                Directory.CreateDirectory(str27);
                FileUtil.CopyFileOrDirectory(str9, str27 + "/TROPHY.TRP");
            }
        }
        else
        {
            ResetTarget(installPath, false);
            EditorUtility.DisplayProgressBar("Building Player", "Linking player", 0.95f);
            string str28 = Path.Combine(playerPackage, !flag4 ? "PS3Player.a" : "PS3PlayerDevelopment.a");
            string str29 = Path.Combine(stagingAreaData, "MonoAssembliesPS3.a");
            string str30 = Path.Combine(stagingArea, str10);
            string str31 = str30 + ".map";
            string str32 = Path.Combine(scePath, "host-win32/ppu/bin/ppu-lv2-gcc.exe");
            string str33 = (((" -fno-exceptions -fno-rtti -mcellppu -mfast-libc -mbranchless -maltivec -msn-ld -mfused-madd -mno-toc -mno-use-save-restore-funcs -Wl,-strip-unused-data -Wl,-strip-duplicates  -Wl,--start-group -L" + scePath + "/target/ppu/lib/hash -lio_stub -lfs_stub -lrtc_stub -lnet_stub  -lsysmodule_stub -lpthread -lspurs_stub -lm -lspurs_jq_stub -lsysutil_stub -lnetctl_stub -lgcm_sys_stub -lgcm_cmd  -lsync_stub -lfios -lsysutil_np_stub -lmic_stub -laudio_stub -lsysutil_avconf_ext_stub -llv2dbg_stub -lovis_stub  -lgem_stub -lcamera_stub -lsysutil_np_trophy_stub -lsysutil_game_stub -lpamf_stub -lsail_stub -lpngenc_stub -lhttp_stub -lhttp_util_stub -lsha1 -lpadfilter ") + " \"" + scePath + "/target/ppu/lib/fno-exceptions/fno-rtti/libc_libent.o\" ") + " \"" + scePath + "/target/ppu/lib/fno-exceptions/fno-rtti/libstdc++_libent.o\" ") + " \"" + scePath + "/target/ppu/lib/fno-exceptions/fno-rtti/libm_libent.o\" ";
            if (!flag4)
            {
                str33 = str33 + " -Wl,--wrap=printf -Wl,--wrap=vprintf -Wl,--wrap=fprintf -Wl,--wrap=vfprintf -Wl,--wrap=puts -Wl,--wrap=fputs ";
            }
            string str57 = str33;
            str33 = (str57 + " \"" + str28 + "\"  \"" + str29 + "\"  -Wl,--end-group -o \"" + str30 + "\"") + " -Wl,-Map=\"" + str31 + "\" ";
            ExternalTool.StartProcess(str32, str33, str30, true, string.Empty);
            File.Copy(Path.Combine(stagingArea, str10), Path.Combine(str15, str10));
            Directory.Delete(to, true);
            string str34 = !needsDrm ? "PS3_GAME" : GetTitleConfigValue(xmlFileName, "TITLE");
            string str35 = stagingArea + "/" + str34;
            if (!Directory.Exists(str35))
            {
                Directory.CreateDirectory(str35);
            }
            string str36 = str35 + "/USRDIR";
            string str37 = str36 + "/Media";
            string str38 = str34 + "/USRDIR/EBOOT.BIN";
            string destFileName = str15 + "/EBOOT.BIN.MAP";
            string str40 = str34 + "/PARAM.SFO";
            FileUtil.DeleteFileOrDirectory(str36);
            if (!Directory.Exists(str36))
            {
                Directory.CreateDirectory(str36);
            }
            FileUtil.MoveFileOrDirectory(stagingAreaData, str37);
            EditorUtility.DisplayProgressBar("Building Player", "Preparing for packaging", 0.96f);
            if (flag4)
            {
                FileUtil.CopyFileOrDirectory(Path.Combine(stagingArea, str10), Path.Combine(stagingArea, str10 + ".stripped"));
            }
            else
            {
                string str41 = Path.Combine(stagingArea, str10 + ".stripped");
                string str42 = Path.Combine(scePath, "host-win32/ppu/bin/ppu-lv2-strip");
                string[] textArray3 = new string[] { " -g -S -d --strip-debug -x --strip-unneeded -s \"", Path.Combine(stagingArea, str10), "\" -o \"", str41, "\" " };
                string str43 = string.Concat(textArray3);
                ExternalTool.StartProcess(str42, str43, str41, true, string.Empty);
            }
            string str44 = Path.Combine(stagingArea, str38);
            string str45 = Path.Combine(scePath, !needsDrm ? "host-win32/bin/make_fself" : "host-win32/bin/make_fself_npdrm");
            string[] textArray4 = new string[] { " \"", Path.Combine(stagingArea, str10), ".stripped\" \"", str44, "\"" };
            string str46 = string.Concat(textArray4);
            ExternalTool.StartProcess(str45, str46, str44, true, string.Empty);
            FileUtil.DeleteFileOrDirectory(Path.Combine(stagingArea, str10 + ".stripped"));
            EditorUtility.DisplayProgressBar("Building Player", "Generating system file", 0.97f);
            string buildToolsDirectory = BuildPipeline.GetBuildToolsDirectory(BuildTarget.PS3);
            string str48 = Path.Combine(stagingArea, str40);
            string str49 = Path.Combine(buildToolsDirectory, "ps3cmd.exe");
            string[] textArray5 = new string[] { " make_sfo --eboot \"", Path.Combine(stagingArea, str38), "\"  \"", xmlFileName, "\"  \"", str48, "\" " };
            string str50 = string.Concat(textArray5);
            ExternalTool.StartProcess(str49, str50, str48, true, string.Empty);
            if (File.Exists(str7))
            {
                FileUtil.CopyFileOrDirectory(str7, str35 + "/PIC1.PNG");
            }
            if (File.Exists(path))
            {
                FileUtil.CopyFileOrDirectory(path, str35 + "/ICON0.PNG");
            }
            if (File.Exists(str8))
            {
                FileUtil.CopyFileOrDirectory(str8, str35 + "/SND0.AT3");
            }
            File.Copy(Path.Combine(stagingArea, str10 + ".map"), destFileName);
            if (flag5)
            {
                string str51 = str35 + "/TROPDIR/" + PlayerSettings.ps3TrophyCommId;
                FileUtil.DeleteFileOrDirectory(str51);
                Directory.CreateDirectory(str51);
                FileUtil.CopyFileOrDirectory(str9, str51 + "/TROPHY.TRP");
            }
            int index = xmlFileName.IndexOf("_TRIAL");
            if (index < 0)
            {
                index = xmlFileName.IndexOf(".XML");
            }
            string str52 = xmlFileName.Substring(0, index) + "_FULL.XML";
            if (File.Exists(str52))
            {
                EditorUtility.DisplayProgressBar("Building Player", "Generating C00 data", 0.97f);
                string str53 = str35 + "/C00";
                FileUtil.DeleteFileOrDirectory(str53);
                Directory.CreateDirectory(str53);
                string str54 = BuildPipeline.GetBuildToolsDirectory(BuildTarget.PS3);
                Process process = new Process {
                    StartInfo = { FileName = Path.Combine(str54, "ps3cmd.exe") }
                };
                string[] textArray6 = new string[] { " make_sfo --eboot \"", str38, "\"  \"", str52, "\"  \"", str34, "/C00/PARAM.SFO\" " };
                process.StartInfo.Arguments = string.Concat(textArray6);
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.WorkingDirectory = stagingArea;
                process.Start();
                process.WaitForExit();
                if ((process.ExitCode != 0) || !File.Exists(Path.Combine(stagingArea, str40)))
                {
                    throw new System.Exception("Failed creating C00 system file! Args: " + process.StartInfo.Arguments);
                }
                if (File.Exists(str7))
                {
                    FileUtil.CopyFileOrDirectory(str7, str53 + "/PIC1.PNG");
                }
                if (File.Exists(path))
                {
                    FileUtil.CopyFileOrDirectory(path, str53 + "/ICON0.PNG");
                }
                if (File.Exists(str8))
                {
                    FileUtil.CopyFileOrDirectory(str8, str53 + "/SND0.AT3");
                }
            }
            if (needsDrm)
            {
                EditorUtility.DisplayProgressBar("Building Player", "Packaging", 0.99f);
                Process process2 = new Process {
                    StartInfo = { FileName = Path.Combine(scePath, "host-win32/bin/make_package_npdrm") }
                };
                string[] textArray7 = new string[] { " \"", dLCConfigPath, "\" \"", str34, "\" -o \"", installPath, "\"" };
                process2.StartInfo.Arguments = string.Concat(textArray7);
                process2.StartInfo.UseShellExecute = true;
                process2.StartInfo.WorkingDirectory = Path.Combine(Directory.GetCurrentDirectory(), stagingArea);
                process2.Start();
                process2.WaitForInputIdle();
                process2.WaitForExit();
                if (process2.ExitCode != 0)
                {
                    throw new System.Exception("Failed packaging project! " + process2.StartInfo.FileName + process2.StartInfo.Arguments);
                }
            }
            else
            {
                FileUtil.DeleteFileOrDirectory(installPath + "/PS3_GAME");
                FileUtil.MoveFileOrDirectory(str35, installPath + "/PS3_GAME");
                if (flag5 && flag2)
                {
                    string str55 = installPath + "/TROPDIR/" + PlayerSettings.ps3TrophyCommId;
                    FileUtil.DeleteFileOrDirectory(str55);
                    Directory.CreateDirectory(str55);
                    FileUtil.CopyFileOrDirectory(str9, str55 + "/TROPHY.TRP");
                }
            }
            string str56 = Path.Combine(installPath, "MapFiles");
            if (Directory.Exists(str56))
            {
                FileUtil.DeleteFileOrDirectory(str56);
            }
            Directory.Move(str15, str56);
        }
    }

    internal static void ResetTarget(string fileServingDir, bool reset)
    {
        string processFileName = Path.Combine(Environment.GetEnvironmentVariable("SN_PS3_PATH"), "bin/ps3run.exe");
        string inputArguments = (" -f\"" + fileServingDir + "\" ") + " -h\"" + fileServingDir + "\" ";
        if (reset)
        {
            inputArguments = inputArguments + " -r";
        }
        ExternalTool.StartProcess(processFileName, inputArguments, string.Empty, false, string.Empty);
    }
}

